<!-- 报价单 -->
<template>
  <div class="app-container">
    <el-form inline size="small">
      <!-- 左边为新增按钮 中间是 客户名称、选择日期范围  右侧为查询按钮 -->
      <el-button
        class="mr10"
        type="primary"
        size="small"
        @click="onAddClick"
        icon="el-icon-plus"
      >新增
      </el-button>
      <el-form-item label="客户名称">
        <el-input
          v-model="params.name"
          clearable
          placeholder="请输入客户名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="日期范围">
        <el-date-picker
          type="daterange"
          v-model="dateRange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-button
        class="ml10"
        @click="getList"
        type="primary"
        size="small"
        icon="el-icon-search"
      >查询
      </el-button>
    </el-form>
    <!-- 表格 -->
    <!-- 客户名称、联系人、联系电话、报价人、报价日期、操作（编辑、查看、删除） -->
    <el-table :data="tableData" border stripe @row-dblclick="handleSelect">
      <el-table-column label="报价单编号" prop="quoteCode"></el-table-column>
      <el-table-column label="客户名称" prop="customerName"></el-table-column>
      <el-table-column label="联系人" prop="contactPerson"></el-table-column>
      <el-table-column label="联系电话" prop="contactNo"></el-table-column>
      <el-table-column label="报价人" prop="quoteUserName"></el-table-column>
      <el-table-column label="报价日期" prop="quoteDate"></el-table-column>
      <el-table-column label="报价单状态" prop="quoteStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.quote_status"
            :value="scope.row.quoteStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="330">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-document"
            @click="handlePrintForm(scope.row)"
          >打印
          </el-button>
          <el-button
            type="primary"
            @click="onClickEdit(scope.row)"
            size="mini"
            icon="el-icon-edit"
          >编辑
          </el-button>
          <el-button
            type="primary"
            @click="onViewClick(scope.row)"
            size="mini"
            icon="el-icon-view"
          >查看
          </el-button>
          <el-button
            @click="del(scope.row)"
            type="danger"
            size="mini"
            icon="el-icon-delete"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <!-- 分页 -->
      <el-pagination
        @size-change="onSizeChange"
        @current-change="onCurrentPageChange"
        :current-page="params.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="params.total"
      ></el-pagination>
    </div>

    <!-- 新增/编辑弹窗 -->
    <!-- 上面表单为客户名称、联系人、联系电话、报价人、报价日期 -->
    <!-- 下面表格为序号、类目、描述、单价、数量、总价、备注、操作（编辑、删除） -->
    <el-dialog
      :close-on-click-modal="false"
      title="新增/编辑"
      :visible.sync="dialogFormVisible"
      width="900px"
      append-to-body
      class="form-container"
    >
      <el-form
        inline
        ref="form"
        size="small"
        :rules="rules"
        :model="formData"
        :disabled="isView"
        label-width="7em"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="报价单号"
              prop="quoteCode"
              class="quoteCode"
              :class="{
                'is-required': !formData.isAutoGenerate,
              }"
            >
              <div style="display: flex; align-items: center">
                <el-input
                  v-model="formData.quoteCode"
                  placeholder="请输入报价单号"
                />
                <!-- 是否自动生成开关 -->
                <el-switch
                  style="margin-left: 10px"
                  @change="onAutoGenerateChange"
                  v-model="formData.isAutoGenerate"
                />
                <span style="flex: 1">自动生成</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-select
                v-model="formData.customerName"
                filterable
                :remote="true"
                placeholder="请选择客户"
                style="width: 86%"
                :remote-method="querySearch"
                @change="handleSelectInput"
                :loading="clientLoading"
              >
              </el-select>
              <i
                class="el-icon-search"
                v-if="!isView"
                @click="showSelectClientDialog = true"
                style="
                  margin-left: 10px;
                  font-size: 20px;
                  font-weight: bold;
                  cursor: pointer;
                "
              ></i>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人">
              <el-input
                :readonly="isView"
                v-model="formData.contactPerson"
                placeholder="请输入联系人"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input
                :readonly="isView"
                v-model="formData.contactNo"
                placeholder="请输入联系电话"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="报价单状态" prop="quoteStatus">
              <el-select
                v-model="formData.quoteStatus"
                placeholder="请选择报价单状态"
              >
                <el-option
                  v-for="dict in dict.type.quote_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报价人" prop="quoteUserId">
              <!-- 选择报价人 -->
              <el-select
                :disabled="isView"
                v-model="formData.quoteUserId"
                placeholder="请选择报价人"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="报价日期">
              <el-date-picker
                :disabled="isView"
                v-model="formData.quoteDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                v-model="formData.remark"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 10px;
        "
      >
        <div style="font-size: 16px; font-weight: bold">商品信息</div>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="onAddGoodsClick"
          v-if="!isView"
        >选择商品
        </el-button>
      </div>
      <!-- 表格 -->
      <!-- 序号、商品编码、商品名称、规格型号、单位、数量、单价、小计、备注、操作（编辑、删除） -->
      <el-table :data="formData.orderDetails" border stripe>
        <!--        <el-table-column type="index" width="50"/>-->
        <el-table-column prop="quoteOrderDetailId" label="id"/>
        <el-table-column prop="itemCode" label="商品编码"/>
        <el-table-column prop="itemName" label="商品名称"/>
        <el-table-column
          label="产品物料图片"
          prop="itemImage"
          align="center"
          width="100px"
        >
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px; margin-bottom: -4px"
              :src="`${baseUrl}` + scope.row.itemImage"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格型号"/>
        <el-table-column prop="unitOfMeasure" label="单位"/>
        <el-table-column prop="num" label="数量"/>
        <el-table-column prop="unitPrice" label="单价"/>
        <el-table-column prop="total" label="小计"/>
        <el-table-column prop="remark" label="备注"/>
        <el-table-column label="操作" width="150px" v-if="!isView">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleEditGoods(scope.row, scope.$index)"
            >编辑
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="handleDeleteGoods(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="font-size: 16px; font-weight: bold">其他费用信息</div>
      <!-- 成本合计、报价 -->
      <el-form label-width="80px" inline class="mt10">
        <el-row>
          <el-col :span="8">
            <el-form-item label="灌装人工">
              <el-input
                :readonly="isView"
                type="number"
                v-model="formData.gzgrPrice"
                placeholder="请输入灌装人工费用"
                :min="1"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="包装人工">
              <el-input
                :readonly="isView"
                type="number"
                v-model="formData.bzgrPrice"
                placeholder="请输入包装人工费用"
                :min="1"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运费">
              <el-input
                :readonly="isView"
                type="number"
                v-model="formData.yfPrice"
                placeholder="请输入运费"
                :min="1"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="行政管理">
              <el-input
                :readonly="isView"
                type="number"
                v-model="formData.xzglPrice"
                placeholder="请输入行政管理费用"
                :min="1"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="损耗">
              <el-input
                :readonly="isView"
                type="number"
                v-model="formData.shPrice"
                placeholder="请输入损耗费用"
                :min="1"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税费">
              <el-input
                :readonly="isView"
                type="number"
                v-model="formData.sfPrice"
                placeholder="请输入税费"
                :min="0.01"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="FOB费用">
              <el-input
                :readonly="isView"
                type="number"
                v-model="formData.fobPrice"
                placeholder="请输入FOB费用"
                :min="1"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="成本合计">
          ￥{{
            getTotalPrice()
          }}元
        </el-form-item>
        <el-form-item label="报价">
          <el-input
            :readonly="isView"
            type="number"
            v-model="formData.quotePrice"
            placeholder="请输入报价"
            :min="1"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <template v-if="!isView">
          <el-button type="primary" @click="submit" v-if="!formData.id"
          >新增
          </el-button>
          <el-button type="primary" @click="submit" v-else>修改</el-button>
        </template>
      </div>
    </el-dialog>
    <!-- 新增商品弹窗 -->
    <!-- 表单为类目、描述、单价、数量、总价、备注（复选框） -->
    <el-dialog
      :close-on-click-modal="false"
      title="新增商品"
      :visible.sync="dialogGoodsVisible"
    >
      <el-form label-width="80px">
        <el-form-item label="类目">
          <el-input
            v-model="goodForm.categoryName"
            placeholder="请输入类目"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="goodForm.description"
            placeholder="请输入描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="单价">
          <el-input
            v-model.number="goodForm.unitPrice"
            placeholder="请输入单价"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input
            v-model.number="goodForm.quantity"
            placeholder="请输入数量"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="总价">
          <el-input
            :value="calculateTotalPrice"
            placeholder="自动计算总价"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="goodForm.comment"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 取消、确认 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogGoodsVisible = false">取 消</el-button>
        <el-button type="primary" @click="onConfirmAddGoods">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 商品编码、商品名称、规格型号、单位、数量、单价、小计、备注 -->
    <el-dialog
      title="选择商品"
      :visible.sync="showAddGoodsDialog"
      width="500px"
    >
      <el-form
        label-width="6em"
        ref="addGoodsRef"
        size="small"
        :model="addGoodsForm"
        :rules="addGoodsRules"
      >
        <el-form-item label="商品编码" prop="itemCode">
          <el-input
            disabled
            style="width: 90%"
            v-model="addGoodsForm.itemCode"
            clearable
            placeholder="请输入商品编码"
          ></el-input>
          <i
            class="el-icon-search"
            @click="showSelectGoodsDialog = true"
            style="
              margin-left: 10px;
              font-size: 20px;
              font-weight: bold;
              cursor: pointer;
            "
          ></i>
        </el-form-item>

        <el-form-item label="商品名称" prop="itemName">
          <el-input
            disabled
            v-model="addGoodsForm.itemName"
            clearable
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品图片" prop="itemImage">
          <ImageUpload
            :value="`${baseUrl}` + addGoodsForm.itemImage"
            @onUploaded="handleImgUplaoded"
            @onRemoved="handleImgRemoved"
            :limit="1"
            :fileSize="1"
            :fileType="['png', 'jpg']"
            title="图片大小不超过156kb，图片格式为PNG"
          />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input
            v-model="addGoodsForm.specification"
            clearable
            disabled
            placeholder="请输入规格型号"
          ></el-input>
        </el-form-item>

        <el-form-item label="单位" prop="unitOfMeasure">
          <el-input
            disabled
            v-model="addGoodsForm.unitOfMeasure"
            clearable
            placeholder="请输入单位"
          ></el-input>
        </el-form-item>

        <el-form-item label="数量" prop="num">
          <el-input
            v-model="addGoodsForm.num"
            clearable
            type="number"
            placeholder="请输入数量"
          ></el-input>
        </el-form-item>

        <el-form-item label="单价" prop="unitPrice">
          <el-input
            v-model="addGoodsForm.unitPrice"
            clearable
            type="number"
            placeholder="请输入单价"
          ></el-input>
        </el-form-item>

        <el-form-item label="小计" prop="total">
          <el-input
            disabled
            v-model="addGoodsForm.total"
            clearable
            placeholder="请输入小计"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addGoodsForm.remark"
            clearable
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddGoodsDialog = false">取消</el-button>
        <el-button class="ml10" @click="addGoods" type="primary" size="small"
        >确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      width="1100px"
      :visible.sync="showSelectGoodsDialog"
    >
      <mditem :isComponent="true" @select="onSelectGoods"/>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      width="1100px"
      :visible.sync="showSelectClientDialog"
    >
      <client :isComponent="true" @select="onSelectClient"/>
    </el-dialog>
    <!-- 打印弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      title="打印"
      width="1100px"
      :visible.sync="showPrintDialog"
    >
      <RIframe v-if="showPrintDialog" :src="currentPrintUrl"/>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import {listUser} from "@/api/system/user";
import RIframe from "@/components/iFrame/index.vue";
import moment from "moment";
import {genCode} from "@/api/system/autocode/rule";
import {listClient} from "@/api/mes/md/client";
import {addQuote, updateQuote} from "@/api/mes/md/quote";
import client from "@/views/mes/md/client/index.vue";
import _ from "lodash";
import mditem from "@/views/mes/md/mditem/index.vue";

export default {
  name: "Quote",
  props: {
    isComponent: {
      type: Boolean,
      default: false,
    },
  },
  dicts: ["quote_status"],
  mounted() {
    this.getList();
    listUser({
      pageNum: 1,
      pageSize: 9999,
    }).then((res) => {
      this.userList = res.rows;
    });
    this.getUserInfo();
  },

  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      currentPrintUrl: "",
      showPrintDialog: false,
      clientLoading: false,
      showSelectClientDialog: false,
      showSelectGoodsDialog: false,
      showAddGoodsDialog: false,
      clientList: [],
      tableData: [],
      dateRange: [],
      formData: {
        quoteCode: "",
        customerName: "",
        contactPerson: "",
        contactNo: "",
        quoteDate: moment().format("YYYY-MM-DD"),
        quoteUserId: "",
        quoteStatus: "",
        remark: "",
        orderDetails: [],
      },
      params: {
        name: "",
        startDate: "",
        endDate: "",
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      goodForm: {
        categoryName: "",
        description: "",
        unitPrice: 0,
        quantity: 0,
        comment: "",
      },
      isEdit: false,
      dialogFormVisible: false,
      addTableData: [
        {
          index: "1",
          category: "类目1",
          description: "描述1",
          unitPrice: "100",
          quantity: "1",
          totalPrice: "100",
          remark: "备注1",
        },
        {
          index: "2",
          category: "类目2",
          description: "描述2",
          unitPrice: "200",
          quantity: "2",
          totalPrice: "400",
          remark: "备注2",
        },
        {
          index: "3",
          category: "类目3",
          description: "描述3",
          unitPrice: "300",
          quantity: "3",
          totalPrice: "900",
          remark: "备注3",
        },
        {
          index: "4",
          category: "类目4",
          description: "描述4",
          unitPrice: "400",
          quantity: "4",
          totalPrice: "1600",
          remark: "备注4",
        },
        {
          index: "5",
          category: "类目5",
          description: "描述5",
          unitPrice: "500",
          quantity: "5",
          totalPrice: "2500",
          remark: "备注5",
        },
        {
          index: "6",
          category: "类目6",
          description: "描述6",
          unitPrice: "600",
          quantity: "6",
          totalPrice: "3600",
          remark: "备注6",
        },
      ],
      dialogGoodsVisible: false,
      userList: [],
      userInfo: {},
      isView: false,
      addGoodsForm: {
        itemCode: "",
        itemName: "",
        specification: "",
        unitOfMeasure: "",
        num: "",
        unitPrice: "",
        total: "",
        remark: "",
      },
      rules: {
        quoteCode: [
          {required: true, message: "报价单编号不能为空", trigger: "blur"},
        ],
        quoteStatus: [
          {required: true, message: "报价单状态不能为空", trigger: "blur"},
        ],
        quoteUserId: [
          {required: true, message: "报价人不能为空", trigger: "blur"},
        ],
      },
      addGoodsRules: {
        itemCode: [
          {required: true, message: "请输入商品编码", trigger: "blur"},
        ],
        itemName: [
          {required: true, message: "请输入商品名称", trigger: "blur"},
        ],
        // specification: [
        //   { required: true, message: "请输入规格型号", trigger: "blur" },
        // ],
        unitOfMeasure: [
          {required: true, message: "请输入单位", trigger: "blur"},
        ],
        num: [{required: true, message: "请输入数量", trigger: "blur"}],
        unitPrice: [{required: true, message: "请输入单价", trigger: "blur"}],
        remark: [{required: false, trigger: "blur"}],
      },
    };
  },
  watch: {
    // addGoodsForm.total
    "addGoodsForm.num"(val) {
      this.addGoodsForm.total = val * this.addGoodsForm.unitPrice;
    },
    "addGoodsForm.unitPrice"(val) {
      this.addGoodsForm.total = val * this.addGoodsForm.num;
    },
  },
  methods: {
    //图片上传成功
    handleImgUplaoded(imgUrl) {
      this.addGoodsForm.itemImage = imgUrl;
    },
    //图片移除
    handleImgRemoved(imgUrl) {
      this.addGoodsForm.itemImage = null;
    },
    handleSelect(row) {
      this.$emit("select", row);
    },
    onViewClick(row) {
      this.dialogFormVisible = true;
      this.isView = true;
      request({
        url: `/mes/md/quotation-order/${row.id}`,
        method: "get",
      }).then((res) => {
        this.formData = res.data;
      });
    },
    getTotalPrice() {
      let orderDetailPrices = this.formData.orderDetails.reduce((total, orderDetail) => {
        return total + orderDetail.unitPrice * orderDetail.num;
      }, 0);
      let otherPrices = parseFloat(this.formData.gzgrPrice == null ? 0.0 : this.formData.gzgrPrice)
        + parseFloat(this.formData.bzgrPrice == null ? 0.0 : this.formData.bzgrPrice)
        + parseFloat(this.formData.yfPrice == null ? 0.0 : this.formData.yfPrice)
        + parseFloat(this.formData.xzglPrice == null ? 0.0 : this.formData.xzglPrice)
        + parseFloat(this.formData.shPrice == null ? 0.0 : this.formData.shPrice)
        + parseFloat(this.formData.sfPrice == null ? 0.0 : this.formData.sfPrice)
        + parseFloat(this.formData.fobPrice == null ? 0.0 : this.formData.fobPrice);
      return orderDetailPrices + otherPrices;
    },
    // 获取个人信息
    getUserInfo() {
      request({
        url: "/system/user/profile",
        method: "get",
      }).then((res) => {
        this.userInfo = res.data;
        this.formData.quoteUserId = this.userInfo.userId;
      });
    },
    querySearch(query) {
      if (query !== "") {
        listClient({
          clientName: query,
        }).then((response) => {
          this.clientLoading = false;
          this.clientList = response.rows;
        });
      } else {
        this.clientList = [];
      }
    },
    handleSelectInput(val) {
      const client = this.clientList.find((item) => item.clientName === val);
      this.onSelectClient(client);
    },
    onSelectClient(client) {
      this.showSelectClientDialog = false;
      this.formData.customerName = client.clientName;
      this.formData.contactPerson = client.clientName;
      this.formData.contactNo = client.tel;
    },
    onAutoGenerateChange(val) {
      if (this.formData.isAutoGenerate) {
        genCode("QUOTE_CODE").then((res) => {
          console.log(res);
          this.$set(this.formData, "quoteCode", res);
        });
      } else {
        this.formData.quoteCode = "";
      }
    },
    handleEditGoods(row, index) {
      console.log(row);
      this.addGoodsForm = _.cloneDeep({
        ...row,
        index,
      });
      this.showAddGoodsDialog = true;
      this.isGoodsEdit = true;
    },
    onSelectGoods(goods) {
      this.showSelectGoodsDialog = false;
      this.addGoodsForm.itemCode = goods.itemCode;
      this.addGoodsForm.itemName = goods.itemName;
      this.addGoodsForm.itemImage = goods.itemImage;
      this.addGoodsForm.specification = goods.specification;
      this.addGoodsForm.unitOfMeasure = goods.unitOfMeasure;
      this.addGoodsForm.itemImage = goods.itemImage;
    },
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.formData.id) {
            // 修改
            updateQuote(this.formData, this.formData.id).then((res) => {
              if (res.code === 200) {
                this.$message({
                  type: "success",
                  message: "修改成功!",
                });
                this.dialogFormVisible = false;
                this.getList();
              } else {
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
            });
            return;
          }
          addQuote(this.formData).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "新增成功!",
              });
              this.dialogFormVisible = false;
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    async onConfirmAddGoods() {
      if (this.goodForm.quoteOrderDetailId) {
        // 进入编辑状态
        // put http://121.36.231.1/prod-api/mes/md/quotation-order/item/3
        await request({
          url: `/mes/md/quotation-order/updateItem`,
          method: "put",
          data: this.goodForm,
        }).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "编辑成功!",
            });
          }
        });
      } else {
        if (this.formData.quoteOrderDetailId) {
          this.goodForm.quoteOrderCode = this.formData.quoteCode;
          // 调接口新增
          await request({
            url: `/mes/md/quotation-order/addItem`,
            method: "post",
            data: {
              ...this.goodForm,
            },
          });
          // 重新获取数据
          await request({
            url: `/mes/md/quotation-order/${this.formData.id}`,
            method: "get",
          }).then((res) => {
            this.formData.orderDetails = res.data.items;
          });
        } else {
          this.formData.orderDetails.push(this.goodForm);
        }
        this.$message({
          type: "success",
          message: "新增成功!",
        });
      }
      this.dialogGoodsVisible = false;
    },
    onAddGoodsClick() {
      this.isGoodsEdit = false;
      // 清空
      this.addGoodsForm = {
        itemCode: "",
        itemName: "",
        specification: "",
        unitOfMeasure: "",
        num: "",
        unitPrice: "",
        total: "",
        remark: "",
      };
      this.showAddGoodsDialog = true;
    },
    addGoods() {
      this.$refs["addGoodsRef"].validate((valid) => {
        if (valid) {
          if (this.isGoodsEdit) {
            // 判断addForm是否有id
            if (this.addGoodsForm.quoteOrderDetailId) {
              // 修改
              request({
                url: "mes/md/quotation-order/updateItem",
                method: "put",
                data: {...this.addGoodsForm},
              }).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: "success",
                    message: "修改成功!",
                  });
                  this.formData.orderDetails = this.formData.orderDetails.map(
                    (item) => {
                      if (
                        item.quoteOrderDetailId ===
                        this.addGoodsForm.quoteOrderDetailId
                      ) {
                        return this.addGoodsForm;
                      }
                      return item;
                    }
                  );
                  this.showAddGoodsDialog = false;
                } else {
                  this.$message({
                    type: "error",
                    message: res.msg,
                  });
                }
              });
              return;
            }

            if (!this.formData.id) {
              this.$set(
                this.formData.orderDetails,
                this.addGoodsForm.index,
                this.addGoodsForm
              );
              this.showAddGoodsDialog = false;
            }
          } else {
            if (this.formData.id) {
              // 调接口直接添加
              request({
                url: `/mes/md/quotation-order/addItem`,
                method: "post",
                data: {
                  ...this.addGoodsForm,
                  quoteOrderCode: this.formData.quoteCode,
                },
              }).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: "success",
                    message: "新增成功!",
                  });
                  request({
                    url: "/mes/md/quotation-order/" + this.formData.id,
                    method: "get",
                  }).then((res) => {
                    this.formData.orderDetails = res.data.orderDetails;
                  });
                  this.showAddGoodsDialog = false;
                } else {
                  this.$message({
                    type: "error",
                    message: res.msg,
                  });
                }
              });
            } else {
              this.formData.orderDetails.push({
                ...this.addGoodsForm,
              });
              this.showAddGoodsDialog = false;
            }
          }
        } else {
          return false;
        }
      });
    },
    handleDeleteGoods(row) {
      // 提示是否确认
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //  如果不存在id，则直接删除这条
          if (!row.quoteOrderDetailId) {
            this.formData.orderDetails = this.formData.orderDetails.filter(
              (item) => item !== row
            );
            return;
          }
          // http://localhost:8080/mes/wm/productSalseOrderDetail/{{salseOrderDetailId}}
          request({
            url: "/mes/md/quotation-order/item/" + row.quoteOrderDetailId,
            method: "delete",
          }).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.formData.orderDetails = this.formData.orderDetails.filter(
                (item) => item !== row
              );
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    onAddClick() {
      this.isView = false;
      this.formData = {
        customerName: "",
        contactPerson: "",
        contactNo: "",
        quoteDate: moment().format("YYYY-MM-DD"),
        quoteUserId: this.userInfo.userId,
        orderDetails: [],
      };
      this.dialogFormVisible = true;
      this.formData.isAutoGenerate = true;
      this.onAutoGenerateChange();
    },
    handlePrintForm(row) {
      this.isView = false;
      //http://localhost:8080/mes/wm/purchaseOrder/{{purchaseOrderId}}
      this.currentPrintUrl = `${location.origin}/prod-api/jmreport/view/908160857549811712?token=Bearer%20eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjEzMDhiZWVlLTI5MjktNDUwYS04MmQ5LWYxZmU5YmRiYzJlZiJ9.nEZT_cInaYyLzND8pCayC80yBsrE8iP0Wsq8lfVsOfRK033IeAb4iRkgJK56EaNYyKbcBaY-_vtmp-i0W6pRjQ&orderId=${row.id}`;
      this.showPrintDialog = true;
    },
    onClickEdit(row) {
      this.isView = false;
      this.dialogFormVisible = true;
      request({
        url: `/mes/md/quotation-order/${row.id}`,
        method: "get",
      }).then((res) => {
        this.formData = res.data;
      });
    },
    formatTotalPrice(row) {
      return row.unitPrice * row.quantity;
    },
    editItem(row) {
      this.goodForm = row;
      this.dialogGoodsVisible = true;
    },
    deleteItem(row) {
      // 判断是否有id
      if (row.id) {
        // 有id，删除数据库中的数据
        request({
          url: `/mes/md/quotation-order/item/${row.id}`,
          method: "delete",
        }).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            // 重新获取数据
            request({
              url: `/mes/md/quotation-order/${this.formData.id}`,
              method: "get",
            }).then((res) => {
              this.formData.items = res.data.items;
            });
          }
        });
      } else {
        // 没有id，删除表格中的数据
        this.formData.items = this.formData.items.filter(
          (item) => item.index !== row.index
        );
      }
    },
    async onConfirmAddquote() {
      if (this.formData.id) {
        // 进入编辑状态
        // put http://121.36.231.1/prod-api/mes/md/quotation-order/7
        await request({
          url: `/mes/md/quotation-order/${this.formData.id}`,
          method: "put",
          data: this.formData,
        }).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "编辑成功!",
            });
          }
        });
      } else {
        await request({
          url: "/mes/md/quotation-order",
          method: "post",
          data: this.formData,
        }).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "新增成功!",
            });
          }
        });
      }
      this.getList();
      this.dialogFormVisible = false;
    },
    del(row) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          request({
            url: `/mes/md/quotation-order/${row.id}`,
            method: "delete",
          }).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getList() {
      if (this.dateRange && this.dateRange.length) {
        this.params.startDate = moment(this.dateRange[0]).format("YYYY/MM/DD");
        this.params.endDate = moment(this.dateRange[1]).format("YYYY/MM/DD");
        console.log(this.params);
      } else {
        this.params.startDate = "";
        this.params.endDate = "";
      }
      console.log(this.params);

      request({
        url: "/mes/md/quotation-order/list",
        method: "get",
        params: this.params,
      }).then((res) => {
        this.tableData = res.rows;
        this.params.total = res.total;
      });
    },
    onSizeChange(val) {
      this.params.pageSize = val;
      this.getList();
    },
    onCurrentPageChange(val) {
      this.params.pageNum = val;
      this.getList();
    },
    add() {
    },
  },

  components: {
    mditem,
    client,
    RIframe,
  },

  computed: {
    calculateTotalPrice() {
      return this.goodForm.unitPrice * this.goodForm.quantity;
    },
  },
};
</script>
<style lang="scss" scoped>
.page {
  text-align: right;
  margin-top: 10px;
}

.form-container {
  ::v-deep {
    .el-form-item {
      min-width: 290px;
      margin-bottom: 15px;
      display: inline-flex;
      align-items: center;
    }

    .el-form-item__content {
      display: inline-flex;
      align-items: center;
    }

    .el-input {
      width: 160px;
    }
  }
}
</style>
